import 'dart:convert';
import 'dart:io';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:appscheme/appscheme.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:get/get.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';
import 'package:oktoast/oktoast.dart';
import 'package:package_info/package_info.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/event_bus.dart';
import 'package:yp/jpusher.dart';
import 'package:yp/logic.dart';
import 'package:yp/utils/util.dart';

import 'config/cg_umeng_analysis.dart';
import 'config/config.dart';
import 'config/theme.dart';
import 'helper.dart';
import 'http/dio_api.dart';
import 'router.dart';

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() {
    return _MyAppState();
  }
}

/// 继承WidgetsBindingObserver
class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  DateTime lastTime;

  @override
  void initState() {
    super.initState();
    if (!kIsWeb) {
      if (Platform.isAndroid) {
        WidgetsBinding.instance.addObserver(this);
      }

    }
    /// 同意协议时 初始化
    // _initPackage();

    // eventBus.on<InitPackage>().listen((event) {
    //   // _initPackage();
    //   initUmengAnalytics();
    // });

    /// 同意协议的话 直接初始化
    // if (!kIsWeb) {
    //   bool isAgree = SpUtil.getBool("isAgree", defValue: false);
    //   if (isAgree) {
    //     // _initPackage();
    //     initUmengAnalytics();
    //   }
    // }

    /// 初始化Dio
    DioApi.getInstance();

    //// 只在app初始化
    if (!kIsWeb) {
      if (Platform.isAndroid) {
        SystemChrome.setSystemUIOverlayStyle(
          SystemUiOverlayStyle(statusBarColor: Colors.transparent),
        );
      }

      /// deeplink
      AppScheme appScheme = AppSchemeImpl.getInstance();
      appScheme.getInitScheme().then((value) {
        if (value != null) {
          // toast("Init  ${value.dataString}");
          /// app初始化启动
          _jumpPage(value.query);
        }
      });
      appScheme.getLatestScheme().then((value) {
        if (value != null) {
          // toast("map:${value.query}");
        }
      });

      appScheme.registerSchemeListener().listen((event) {
        if (event != null) {
          // toast("listen ${event.dataString}  map:${event.query}");
          _jumpPage(event.query);
        }
      });

      //// 微信
      // fluwx.registerWxApi(
      //   appId: Config.WECHAT_APPID,
      //   doOnAndroid: true,
      //   doOnIOS: true,
      //   universalLink: Config.UNIVERSAL_LINK,
      // );
      // fluwx.weChatResponseEventHandler.listen((event) {
      //   if (event is fluwx.WeChatLaunchMiniProgramResponse) {
      //     /// 取消支付：extMsg:{"errMsg":"requestPayment:fail cancel","status":"30"}
      //     /// 支付成功 extMsg:{"errMsg":"requestPayment:ok","status":"20"}
      //     Map resultMap = json.decode(event.extMsg);
      //     print("支付结果");
      //     print(SpUtil.getString('dingdan'));
      //     if (resultMap != null) {
      //       if (resultMap["status"].toString() == "20") {
      //         toast("支付成功");
      //         setMoneyOver(
      //             SpUtil.getString('dingdan'), 1, 'Complete', 'success', 'a');
      //       } else {
      //         toast("支付失败");
      //         setMoneyOver(SpUtil.getString('dingdan'), 0, 'List', 'err', 'a');
      //       }
      //     } else {
      //       setMoneyOver(SpUtil.getString('dingdan'), 0, 'List', 'err', 'a');

      //       toast("支付失败");
      //     }
      //   }
      // });
    }

    // WidgetsBinding.instance.addObserver(this);
  }

  // Future<void> initUmengAnalytics() async {
  //    var result = await UmengAnalyticsPlugin.init(
  //      androidKey: Config.CGHSHUmengAppKeyForAndroid,
  //      iosKey: Config.CGHSHUmengAppKeyForIOS,
  //    );

  //    print('Umeng initialized.' + result.toString());
  // }

  // void _initMainShopData() {
  //   SpUtil.putInt(Config.IS_CHANGE_SHOP, 0);
  //   SpUtil.remove(Config.GET_SHOP_INFO);
  // }

  @override
  void dispose() {
    if (!kIsWeb) {
      if (Platform.isAndroid) {
        WidgetsBinding.instance.removeObserver(this);
      }
    }
    super.dispose();
  }

  /// 只在同意协议后初始化
  // _initPackage() async {
  //   if (!kIsWeb) {
  //     //fluwx不支持web
  //     initUmengAnalytics();

  //     // https://da6lk9.xinstall.com.cn/tolink/
  //     // // await AmapCore.init('65d67aa3bd7504703c0c56649ac35810');
  //     // AMapFlutterLocation.setApiKey("0ec615c7bf17e43e31cf3222e3ad36ec", "32fa3a9e1c00c4fc17131f51b17a1a31");
  //     Config.AMap_ios_get = Config.AMap_ios;
  //     if (GetPlatform.isIOS) {
  //       PackageInfo packageInfo = await PackageInfo.fromPlatform();
  //       var packageName = packageInfo.packageName;
  //       if (packageName == 'com.zrhsh') {
  //         Config.AMap_ios_get = Config.AMap_ios_com;
  //       }
  //     }
  //     AMapFlutterLocation.setApiKey(Config.AMap_andriod, Config.AMap_ios_get);
  //     //因为jpush_flutter插件目前不支持web
  //     // Future.delayed(Duration(seconds: 1), () {
  //     //   JPushMan().initJpush();
  //     // });
  //   }
  // }

  /// 重写 didChangeAppLifecycleState
  @override
  void didChangeAppLifecycleState(AppLifecycleState state)  {
    if (Config.ShowLoginPageLeftTip==false){
      return;
    }
    super.didChangeAppLifecycleState(state);
        switch (state) {
          case AppLifecycleState.resumed:
            print("程序从后台返回前台");
           // toast("您刚才离开了壹品慧应用");
            break;
          case AppLifecycleState.inactive:
            print('应用程序处于非活动状态，并且未接收用户输入');
            toast("您刚刚离开了壹品慧应用");
            break;
          case AppLifecycleState.paused:
            print('程序从前台退出到后台');
           // toast("壹品慧应用处于后台运行状态");
            break;
          case AppLifecycleState.detached:
            print('应用程序将暂停');
           // toast("壹品慧应用即将被关闭");
            break;
          default:
            print('监听应用程序状态');
        }

  }

  @override
  Widget build(BuildContext context) {
    var state = Get.find<GlobalLogic>().state;
    bool isLogin = SpUtil.getString(Config.TOKEN, defValue: "").isNotEmpty;
    return ScreenUtilInit(
      designSize: Size(750, 1334),
      builder: () => OKToast(
        child: WillPopScope(
          child: RefreshConfiguration(
            hideFooterWhenNotFull: true, //列表数据不满一页,不触发加载更多
            child: GetMaterialApp(
              theme: ypThemeData,
              title: '壹品慧',
              builder: (ctx, child) {
                /// 2022-01-17 下面这一行报错的话 库升级一下 不然ios会报错
                ScreenUtil.setContext(ctx);
                final easyLoading = EasyLoading.init();
                child = easyLoading(context, child);
                child = MediaQuery(
                  //设置文字大小不随系统设置改变
                  data: MediaQuery.of(ctx).copyWith(textScaleFactor: 1.0),
                  child: GestureDetector(
                    onTap: () {
                      FocusScopeNode focus = FocusScope.of(context);
                      if (!focus.hasPrimaryFocus &&
                          focus.focusedChild != null) {
                        FocusManager.instance.primaryFocus.unfocus();
                      }
                    },
                    child: child,
                    // ),
                  ),
                );
                return child;
              },
              debugShowCheckedModeBanner: false,
              localizationsDelegates: [
                GlobalMaterialLocalizations.delegate,
                GlobalWidgetsLocalizations.delegate,
                GlobalCupertinoLocalizations.delegate,
                RefreshLocalizations.delegate,
              ],
              supportedLocales: [
                //const Locale('en'),去掉英文，减小H5包体积
                const Locale('zh'),
              ],
              localeResolutionCallback:
                  (Locale locale, Iterable<Locale> supportedLocales) {
                //print("change language");
                return locale;
              },
              initialRoute: RouteConfig.initialRoute,
              //isLogin? RouteConfig.main : RouteConfig.mallLogin,
              onGenerateRoute: HomeRouter.generateRoute,
              navigatorObservers: kIsWeb ? [] : [CGUmengAppAnalysis()],
              getPages: RouteConfig.getPages,
            ),
          ),
          onWillPop: () async {
            if (lastTime == null ||
                DateTime.now().difference(lastTime) > Duration(seconds: 1)) {
              lastTime = DateTime.now();
              showToast("再次点击退出程序");
              return false;
            }
            return true;
          },
        ),
      ),
    );
  }

  _agreementDialog() {
    showDialog(
      context: Get.context,
      builder: (ctx) {
        return SimpleDialog(
          title: Text(
            '个人信息保护',
            style: TextStyle(
              color: Color(0xff030303),
              fontSize: setWidth(28),
              fontWeight: FontWeight.w600,
            ),
            textAlign: TextAlign.center,
          ),
          titleTextStyle: TextStyle(
              fontSize: 16, fontWeight: FontWeight.bold, color: Colors.blue),
          children: [
            Column(
              children: [
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: setWidth(30),
                  ),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(100)),
                      color: Colors.white),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('感谢您对壹品慧一直以来的信任！'),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Container(
                        child: RichText(
                          text: TextSpan(
                            children: [
                              TextSpan(
                                text: '我们依据最新的监管要求更新了',
                                style: TextStyle(
                                  color: Color(0xff999999),
                                  fontSize: setWidth(22),
                                ),
                              ),
                              TextSpan(
                                  text: '《壹品慧隐私权政策》',
                                  style: TextStyle(
                                    color: Color(0xffEA5504),
                                    fontSize: setWidth(22),
                                  ),
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      Get.toNamed(RouteConfig.webview,
                                          arguments: {
                                            "url":
                                                "https://img.zrhsh.com/zrhshgg/treaty/yszc-yph.html",
                                          });
                                    }),
                              TextSpan(
                                text: '和',
                                style: TextStyle(
                                  color: Color(0xff999999),
                                  fontSize: setWidth(22),
                                ),
                              ),
                              TextSpan(
                                text: '《壹品慧服务协议》',
                                style: TextStyle(
                                  color: Color(0xffEA5504),
                                  fontSize: setWidth(22),
                                ),
                                recognizer: TapGestureRecognizer()
                                  ..onTap = () {
                                    Get.toNamed(RouteConfig.webview,
                                        arguments: {
                                          "url":
                                              "https://img.zrhsh.com/zrhshgg/treaty/yph_fwxy.html",
                                        });
                                  },
                              ),
                              TextSpan(
                                text: '（点击了解更新后的详细内容），特向您说明如下：',
                                style: TextStyle(
                                  color: Color(0xff999999),
                                  fontSize: setWidth(22),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Text(
                        '1、为向您提供缴费相关基本功能，我们会收集、使用必要的信息；',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: setWidth(22),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Text(
                        '2、为保障您的账号与使用安全，您需要授权我们读取本机识别码，您有权拒绝或取消授权，取消后不会影响您使用我们提供的其他服务；',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: setWidth(22),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Text(
                        '3、为在慧生活APP首页向您展示所在位置附近营业厅信息，您需要授权我们获取您的位置权限，您有权拒绝或取消授权，取消后不会影响您使用我们提供的其他服务；',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: setWidth(22),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Text(
                        '4、我们会采取业界先进的安全措施保护您的信息安全；',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: setWidth(22),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Text(
                        '5、未经您同意，我们不会从第三方处获取、共享或向其提供您的信息；',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: setWidth(22),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Text(
                        '6、您可以查询、更正您的个人信息；',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: setWidth(22),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(20),
                      ),
                      Text(
                        '7、您如果选择不同意，则默认退出当前APP',
                        style: TextStyle(
                          color: Color(0xff999999),
                          fontSize: setWidth(22),
                        ),
                      ),
                      SizedBox(
                        height: setWidth(40),
                      ),
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: setWidth(30)),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      GestureDetector(
                        onTap: () async {
                          exit(0);
                        },
                        child: Container(
                          width: setWidth(200),
                          height: setWidth(60),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(
                              Radius.circular(100),
                            ),
                            border: Border.all(color: Color(0xff666666)),
                          ),
                          child: Center(
                            child: Text(
                              "不同意",
                              style: TextStyle(
                                fontSize: setWidth(24),
                                color: Color(0xff666666),
                              ),
                            ),
                          ),
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          SpUtil.putBool("isAgree", true);
                          Get.back();
                        },
                        child: Container(
                          width: setWidth(200),
                          height: setWidth(60),
                          decoration: BoxDecoration(
                            color: Color(0xffEA5504),
                            borderRadius: BorderRadius.all(
                              Radius.circular(100),
                            ),
                            border: Border.all(color: Color(0xffEA5504)),
                          ),
                          child: Center(
                            child: Text(
                              "同意",
                              style: TextStyle(
                                fontSize: setWidth(24),
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                )
              ],
            )
          ],
          backgroundColor: Colors.white,
          elevation: 10,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
        );
      },
    );
  }

  void _jumpPage(Map<String, String> query) {
    Future.delayed(Duration(seconds: 1), () {
      //toast('$query');

      /// 商品详情
      if (query['isGoodsDetail'] != null) {
        Get.toNamed(RouteConfig.goodsDetail, arguments: {
          'itemNumId': query['itemNumId'],
          'styleNumId': query['styleNumId'],
          'shopId': query['shopId'],
          'typeIndex': query['typeIndex'],
        });
      }
      if (query['is_like'] != null) {
        Get.toNamed(RouteConfig.eventDetail, arguments: {
          'is_like': query['is_like'],
          'likes_num': query['likes_num'],
          'view_num': query['view_num'],
          'is_collection': query['is_collection'],
          'series': query['series']
        });
      }
      if (query['g_buy_id'] != null) {
        Get.toNamed(RouteConfig.GroupDetailPage,
            arguments: {'g_buy_id': query['g_buy_id']});
      }

      /// 邀请好友
      if (query['invite_friend'] != null) {
        Get.toNamed(RouteConfig.inviteFriend);
      }

      /// 拼手气红包
      if (query['random_amount'] != null) {
        Get.toNamed(RouteConfig.randomAmount, arguments: {
          "activity_num_id": query['activity_num_id'],
          "event_num_id": query['event_num_id'],
        });
      }
    });
  }
}
